package com.tedu.pj.common.web;

import com.tedu.pj.common.pojo.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/10/15
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {


    @ExceptionHandler(RuntimeException.class)
    public Response Exception(RuntimeException e) {
        log.error("exception {}", e.getMessage());
        return new Response(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(" 参数校验错误", e.getMessage());
        return new Response(e);
    }

    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public Response doHandleShiroException(ShiroException e) {
        Response r = new Response();
        r.setState(0);
        if (e instanceof UnknownAccountException) {
            r.setMsg("账户不存在");
        } else if (e instanceof LockedAccountException) {
            r.setMsg("账户已被禁用");
        } else if (e instanceof IncorrectCredentialsException) {
            r.setMsg("密码不正确");
        } else if (e instanceof AuthorizationException) {
            r.setMsg("没有此操作权限");
        } else {
            r.setMsg("系统维护中");
        }
        e.printStackTrace();
        return r;
    }
}
